package com.android.service;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.SparseIntArray;

public class FileService {

	private DBOpenHelper openHelper;

	public FileService(Context context) {

		openHelper = new DBOpenHelper(context);

	}

	/**
	 * 
	 * 获取每条线程已经下载的文件长度
	 * 
	 * @param path
	 * 
	 * @return
	 */

	public SparseIntArray getData(String path) {

		SQLiteDatabase db = openHelper.getReadableDatabase();

		Cursor cursor = db.rawQuery("select threadid, downlength from filedownlog where downpath=?", new String[] { path });

		SparseIntArray data = new SparseIntArray();

		while (cursor.moveToNext()) {

			data.put(cursor.getInt(0), cursor.getInt(1));

		}

		cursor.close();

		// db.close();

		return data;

	}

	/**
	 * 
	 * 保存每条线程已经下载的文件长度
	 * 
	 * @param path
	 * 
	 * @param map
	 */

	public void save(String path, SparseIntArray array) {// int threadid, int position

		SQLiteDatabase db = openHelper.getWritableDatabase();

		db.beginTransaction();

		try {

			for (int i = 0; i < array.size(); i++) {
				db.execSQL("insert into filedownlog(downpath, threadid, downlength) values(?,?,?)",

				new Object[] { path, i + 1, array.get(i + 1) });
			}

			db.setTransactionSuccessful();

		} finally {

			db.endTransaction();

		}

		// db.close();

	}

	/**
	 * 
	 * 实时更新每条线程已经下载的文件长度
	 * 
	 * @param path
	 * 
	 * @param map
	 */

	public void update(String path, SparseIntArray array) {

		SQLiteDatabase db = openHelper.getWritableDatabase();

		db.beginTransaction();

		try {

			for (int i = 0; i < array.size(); i++) {
				db.execSQL("update filedownlog set downlength=? where downpath=? and threadid=?",

				new Object[] { array.get(i + 1), path, i + 1 });
			}

			db.setTransactionSuccessful();

		} finally {

			db.endTransaction();

		}

		// db.close();

	}

	/**
	 * 
	 * 当文件下载完成后，删除对应的下载记录
	 * 
	 * @param path
	 */

	public void delete(String path) {

		SQLiteDatabase db = openHelper.getWritableDatabase();

		db.execSQL("delete from filedownlog where downpath=?", new Object[] { path });

		db.close();

	}
}